package com.zookeeper.dome;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {

    private String connectString = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        //1获取zookeeper集群
        DistributeClient distributeClient = new DistributeClient();
        distributeClient.getConnect();

        //2注册监听
        distributeClient.getChildren();

        //业务出来
        distributeClient.busServer();
    }

    private void busServer() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getChildren() throws KeeperException, InterruptedException {
        System.out.println("=================start==================");
        List<String> children = zooKeeper.getChildren("/servers", true);
        List<String> hosts = new ArrayList<>();

        for (String child : children) {
            byte[] data = zooKeeper.getData("/servers/" + child, false, null);
            hosts.add(new String(data));
        }
        System.out.println(hosts);
        System.out.println("=================end==================");
    }

    private void getConnect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    System.out.println("============"+watchedEvent);
                    getChildren();

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
